package org.example.gochannel;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class JavaGoChannel<T> {
    private LinkedBlockingQueue<T> queue = null;

    JavaGoChannel() {
    }

    static <E> JavaGoChannel<E> MakeObject(int cache) {
        JavaGoChannel<E> channel = new JavaGoChannel<>();
        channel.queue = new LinkedBlockingQueue<>(cache + 1);
        return channel;
    }

    public static <E> JavaGoChannel<E> Make(int cache) {
        return MakeObject(cache);
    }

    public static <E> JavaGoChannel<E> Make() {
        return MakeObject(0);
    }


    public void in(T t) {
        if (t == null) {
            throw new RuntimeException("offer null");
        }
        queue.offer(t);
    }

    public T out() throws InterruptedException {
        return queue.take();
    }

    public T out(long millsec) throws InterruptedException {
        return queue.poll(millsec, TimeUnit.MILLISECONDS);
    }

    public void clear() {
        queue.clear();
    }

}
